const fs = require('fs');
const path = require('path');
const { initApp, closeApp } = require('./utils/appUtils');

async function main() {
    const clearFlag = () => {
        const exitFlag = path.join(__dirname, 'exit.flag');
        try {
            if (fs.existsSync(exitFlag)) {
                fs.unlinkSync(exitFlag);
            }
        } catch (err) {
            console.error('删除 exit.flag 文件出错', err);
        }
    };

    const exitHandler = async (code) => {
        watcher && watcher.close();
        clearFlag();
        await closeApp(app);
        process.exit(code);
    };

    process.on('exit', async () => {
        await exitHandler(0);
    });

    process.on('SIGINT', async () => {
        await exitHandler(0);
    });

    process.on('uncaughtException', async (error) => {
        console.trace('有一个未捕获的错误', error);
        // await exitHandler(1);
    });

    // 使用信号退出
    process.on('SIGUSR1', async () => {
        console.log('接收到 SIGUSR1 信号，正在退出...');
        await exitHandler(0);
    });

    // 监听文件系统事件
    let watcher = fs.watch(__dirname, async (eventType, filename) => {
        if (eventType === 'rename' && filename === 'exit.flag') {
            console.log('检测到 exit.flag 文件，正在退出...');
            await exitHandler(0);
        }
    });

    // 监听按键事件
    if (process.stdin.isTTY) {
        process.stdin.setRawMode(true);
        process.stdin.resume();
        process.stdin.setEncoding('utf8');

        process.stdin.on('data', async (key) => {
            if (key === '\x1B') {
                console.log('\nESC 键已按下，正在退出...');
                await exitHandler(0);
            }
        });
    }

    // ========= 主程序代码 =========
    // 避免干扰文件，先删除退出标志
    clearFlag();
    const app = {};
    await initApp(app);
    console.log('程序正在运行。按 ESC 键、发信号 SIGUSR1 、创建 "exit.flag" 文件以退出...\n\n');
}

main();
